# 添加地区序列化
from rest_framework import serializers
from areas.models import Area
from users.models import Address


# 定义省市区序列化器
class AreaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = '__all__'


# 定义保存用户信息的序列化器
class AddressSerializer(serializers.ModelSerializer):
    # ( read_only=True前端不用传递该字段到后台进行验证)
    province = serializers.StringRelatedField(label='省', read_only=True)
    city = serializers.StringRelatedField(label='市', read_only=True)
    district = serializers.StringRelatedField(label='区', read_only=True)

    # 重写修改字段，满足前端需要的格式,进行反序列化返回
    province_id = serializers.IntegerField(write_only=True)
    city_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Address
        # fields = '__all__'
        exclude = ('user',)

    # 保存数据到数据库中
    def create(self, validated_data):
        # 获取用户对象
        user = self.context['request'].user

        # 添加user到验证中
        validated_data['user'] = user

        # 调用父类方法
        user = super().create(validated_data)

        return user
